<template>
  <div class="login">
    <el-row class="login-row">
      <el-col :span="6">
        <el-card>
          <div class="tital">zingon文档系统</div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
            <el-form-item prop="username">
              <el-input v-model="ruleForm.username" placeholder="邮箱"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input type="password" placeholder="密码" v-model="ruleForm.password" @keyup.enter.native="submitForm('ruleForm')"></el-input>
            </el-form-item>
            <div class="login-register">
              <router-link to="/register">
                注册
              </router-link>
            </div>
            <div class="login-btn">
              <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
            </div>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { loginByUsername } from "../../api";
import { setToken } from "../../util/auth";
import { Notification } from "element-ui";
export default {
  data: function() {
    return {
      ruleForm: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    submitForm(formName) {
      const self = this;
      self.$refs[formName].validate(valid => {
        if (valid) {
          loginByUsername(self.ruleForm.username, self.ruleForm.password)
            .then(function(resp) {
              if (resp.errmsg === "ok") {
                setToken(resp.data);
                self.$router.push({ path: "/project" });
              }
            })
            .catch(function(e) {
              if (e === "0x0002") {
                Notification.error("邮箱或密码错误。");
              } else if (e === "0x0005") {
                Notification.error("此账户还未激活，请先登陆邮箱进行激活。");
              } else {
                console.log(e);
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.tital {
  text-align: center;
  font-size: 26px;
  margin-bottom: 6%;
}

.login-btn button {
  width: 100%;
  height: 36px;
}

.login {
  display: flex;
  align-items: center;
  height: 100%;
}

.login-row {
  display: flex;
  width: 100%;
  flex-direction: column;
  align-items: center;
}

.login-register {
  text-align: right;
  margin-bottom: 10px;
  margin-right: 10px;
}
</style>